package com.iotproject.studyservice.service.impl;

import com.iotproject.studyservice.entity.StudyGrade;
import com.iotproject.studyservice.entity.StudyWord;
import com.iotproject.studyservice.entity.UserCollectionWord;
import com.iotproject.studyservice.entity.UserUnrememberWord;
import com.iotproject.studyservice.entity.vo.CollectionWord;
import com.iotproject.studyservice.entity.vo.WordDictionaryParts;
import com.iotproject.studyservice.service.*;
import com.iotproject.studyservice.utils.AccessTokenUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import okhttp3.*;
import okhttp3.RequestBody;
import org.json.JSONArray;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TranslateServiceImpl implements TranslateService {

    @Autowired
    StudyGradeService studyGradeService;

    @Autowired
    StudyWordService studyWordService;

    @Autowired
    UserCollectionWordService userCollectionWordService;

    @Autowired
    UserUnrememberWordService userUnrememberWordService;

    //翻译句子
    @Override
    public Map<String, String> sentenceTranslation(String from, String to, String content) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String requestBodyString = "{\"from\":\"" + from + "\",\"to\":\"" + to + "\",\"q\":\"" + content + "\"}";
        RequestBody body = RequestBody.create(mediaType, requestBodyString);
        Request request = new Request.Builder()
            .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans-with-dict/v1?access_token=" + AccessTokenUtils.getAccessToken())
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .build();
        Response response = AccessTokenUtils.HTTP_CLIENT.newCall(request).execute();
        String result = response.body().string();
        JSONObject jsonObject = new JSONObject(result);
        Object resultObject = jsonObject.get("result");
        String resultString = resultObject.toString();
        JSONObject jsonObjectTemp = new JSONObject(resultString);
        JSONArray trans_result = jsonObjectTemp.getJSONArray("trans_result");
        Map<String, String> resultMap = new HashMap<>();
        for (int i = 0; i < trans_result.length(); i++) {
            jsonObjectTemp = trans_result.getJSONObject(i);
            String dst = jsonObjectTemp.get("dst").toString();
            resultMap.put("dst", dst);
        }
        return resultMap;
    }

    //字典
    @Override
    public Map<String, Object> wordDictionary(String word) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        String requestBodyString = "{\"from\":\"" + "en" + "\",\"to\":\"" + "zh" + "\",\"q\":\"" + word + "\"}";
        RequestBody body = RequestBody.create(mediaType, requestBodyString);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans-with-dict/v1?access_token=" + AccessTokenUtils.getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = AccessTokenUtils.HTTP_CLIENT.newCall(request).execute();
        String result = response.body().string();
        JSONObject jsonObject = new JSONObject(result);
        Object resultObject = jsonObject.get("result");
        String resultString = resultObject.toString();
        JSONObject jsonObjectTemp = new JSONObject(resultString);
        JSONArray trans_result = jsonObjectTemp.getJSONArray("trans_result");
        Map<String, Object> resultMap = new HashMap<>();
        List<WordDictionaryParts> partsList = new ArrayList<>();//词性组
        for (int i = 0; i < trans_result.length(); i++) {
            jsonObjectTemp = trans_result.getJSONObject(i);
            String dst = jsonObjectTemp.get("dst").toString();
            resultMap.put("dst", dst);
            String dict = jsonObjectTemp.get("dict").toString();
            jsonObjectTemp = new JSONObject(dict);
            String word_result = jsonObjectTemp.get("word_result").toString();
            jsonObjectTemp = new JSONObject(word_result);
            String simple_means = jsonObjectTemp.get("simple_means").toString();
            jsonObjectTemp = new JSONObject(simple_means);
            JSONArray symbols = jsonObjectTemp.getJSONArray("symbols");
            jsonObjectTemp = symbols.getJSONObject(0);
            if (jsonObjectTemp.has("ph_en")) {
                String ph_en = jsonObjectTemp.get("ph_en").toString();
                resultMap.put("ph_en", ph_en);
            } else {
                resultMap.put("ph_en", "无");
            }
            JSONArray parts = jsonObjectTemp.getJSONArray("parts");
            for (int j = 0; j < parts.length(); j++) {
                jsonObjectTemp = parts.getJSONObject(j);
                String means = jsonObjectTemp.get("means").toString();
                means = means.substring(1, means.length() - 1);
                means = means.replaceAll("\"", "");
                means = means.replaceAll(",", ";");
                String part = jsonObjectTemp.get("part").toString();
                WordDictionaryParts wordDictionaryParts = new WordDictionaryParts();
                wordDictionaryParts.setMeans(means);
                wordDictionaryParts.setPart(part);
                partsList.add(wordDictionaryParts);
            }
        }
        resultMap.put("partsList", partsList);
        return resultMap;
    }

    //如果study-word 不存在该单词，则插入，最终返回该单词的id
    public StudyWord getStudyWordByWD(CollectionWord collectionWord) {
        String name = collectionWord.getName();
        String audio = collectionWord.getAudio();
        String explanation = collectionWord.getExplanation();
        String example = "无";//默认无例句
        //查询等级id
        QueryWrapper<StudyGrade> studyGradeQueryWrapper = new QueryWrapper<>();
        studyGradeQueryWrapper.eq("name", "用户常搜");
        StudyGrade studyGrade = studyGradeService.getOne(studyGradeQueryWrapper);
        String grade = studyGrade.getId();//等级
        //先查询单词是否已经存在
        QueryWrapper<StudyWord> studyWordQueryWrapper = new QueryWrapper<>();
        studyWordQueryWrapper.eq("name", name);
        studyWordQueryWrapper.eq("grade", grade);
        StudyWord studyWord = studyWordService.getOne(studyWordQueryWrapper);
        if (studyWord == null) {//不存在
            //先插入study-word 表
            studyWord = new StudyWord();
            studyWord.setName(name);
            studyWord.setAudio(audio);
            studyWord.setGrade(grade);
            studyWord.setExplanation(explanation);
            studyWord.setExample(example);
            boolean save = studyWordService.save(studyWord);
        }
        return studyWord;//保证存在
    }

    @Override
    public void insertCollectionWordByWD(CollectionWord collectionWord, HttpServletRequest httpServletRequest) {
        StudyWord studyWord = getStudyWordByWD(collectionWord);
        String memberUserId = studyWordService.getMemberUserId(httpServletRequest);
        QueryWrapper<UserCollectionWord> userCollectionWordQueryWrapper = new QueryWrapper<>();
        userCollectionWordQueryWrapper.eq("user_id", memberUserId);
        userCollectionWordQueryWrapper.eq("collection_word_id", studyWord.getId());
        UserCollectionWord userCollectionWord = userCollectionWordService.getOne(userCollectionWordQueryWrapper);
        if (userCollectionWord == null) {
            //加入用户收藏夹
            userCollectionWord = new UserCollectionWord();
            userCollectionWord.setUserId(memberUserId);
            userCollectionWord.setCollectionWordId(studyWord.getId());
            userCollectionWord.setGrade(studyWord.getGrade());
            userCollectionWordService.save(userCollectionWord);
        }
    }

    @Override
    public void insertUnrememberWordByWD(CollectionWord collectionWord, HttpServletRequest httpServletRequest) {
        StudyWord studyWord = getStudyWordByWD(collectionWord);
        //加入用户生词本
        String memberUserId = studyWordService.getMemberUserId(httpServletRequest);
        QueryWrapper<UserUnrememberWord> userUnrememberWordQueryWrapper = new QueryWrapper<>();
        userUnrememberWordQueryWrapper.eq("user_id", memberUserId);
        userUnrememberWordQueryWrapper.eq("unremember_word_id", studyWord.getId());
        UserUnrememberWord userUnrememberWord = userUnrememberWordService.getOne(userUnrememberWordQueryWrapper);
        if (userUnrememberWord == null) {
            userUnrememberWord = new UserUnrememberWord();
            userUnrememberWord.setUserId(memberUserId);
            userUnrememberWord.setUnrememberWordId(studyWord.getId());
            userUnrememberWord.setGrade(studyWord.getGrade());
            userUnrememberWordService.save(userUnrememberWord);
        }
    }


}
